import {fetchDataFklj} from './fetchData';





const invalidateUsers = () => ({
  type: 'INVALIDATE_USERS',
})

const requestUsers = () => ({
  type: 'REQUEST_USERS',
})

const receiveUsers = (json) => ({
  type: 'RECEIVE_USERS_SUCCESS',
  users: json.ryList,
  receivedAt: Date.now()
})





const fetchUsers = (tab) => dispatch => {

  console.log('user-fetchUsers');
  console.log('user-fetchUsers---'+tab);
  dispatch(requestUsers());
  console.log('user-fetchUsers---requestUsers'+tab);

  return fetchDataFklj(tab).then(response => {
    console.log("users-response:",response);
    dispatch(receiveUsers(response))
  }).catch(error => {
    console.log('user-fetchUsers---error');
    dispatch({
      type: 'RECEIVE_USERS_FAILURE',
      error: error,
    })
    
  })
  
}


const shouldFetchUsers = (state) => {
  const users = state.usersFetchState['users']
  if (!users) {
    return true
  }
  //对象存在且正在获取新数据中
  if (users.isFetching) {
    return false
  }
  return users.didInvalidate
}

const fetchUsersIfNeeded = () => (dispatch, getState) => {

  console.log('====================================');
  console.log('fetchUsersIfNeeded');
  console.log('====================================');
    return dispatch(fetchUsers('/dtgkusers'))
  
}

export const RECV_DATA = 'recv-data';
export const RECV_TIMEOUT = 'recv-data-timeout';
export const RECV_ERROR = 'recv-data-error';

export function fetchDataTest() {
    alert('haha');
    return dispatch => {
        fetch('http://localhost:3001')
            .then((res)=>res.json())
            .then((json)=>{
                dispatch(receivedData(json))
            })
            .catch((e)=>{
                dispatch(receiveError(e.toString()))
            });
    }
}

export function receivedData(data) {
    return {type: RECV_DATA, data: data}
}
export function receiveError(message) {
    return {type: RECV_ERROR, message: message}
}


module.exports = {
  invalidateUsers,
  requestUsers,
  receiveUsers,
  fetchUsers,
  fetchUsersIfNeeded,
}